package config

import (
	"database/sql"
	"fmt"
	"time"

	"github.com/go-redis/redis/v8"
	_ "github.com/go-sql-driver/mysql"
)

var (
	// 数据库配置
	DBHost     = "10.2.24.4"
	DBPort     = 3306
	DBUser     = "pointer_xuan"
	DBPassword = "123456"
	DBName     = "gamedb"

	// Redis配置
	RedisHost     = "127.0.0.1"
	RedisPort     = 6379
	RedisPassword = "123456"

	// Session配置
	SessionExpireTime = 10 * time.Minute

	// 邮件服务器配置
	MailHost = "127.0.0.1"
	MailPort = 1234

	// Redis Key模板
	KeyPackage      = "KEY_PACKAGE_%s"  // userid在Redis中使用字符串格式
	KeyPackageExpire = 7 * 24 * 60 * 60 * time.Second
	KeyMailList     = "KEY_MAIL_LIST_%d"
	KeyMailDetail   = "KEY_MAIL_DETAIL_%s"

	// 默认密码
	DefaultSecPassword = "000000"

	// 用户状态
	UserStatusNormal = 0
	UserStatusFreeze = 1

	// 全局连接
	DB    *sql.DB
	Redis *redis.Client
)

// InitDB 初始化数据库连接池
func InitDB() error {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		DBUser, DBPassword, DBHost, DBPort, DBName)

	var err error
	DB, err = sql.Open("mysql", dsn)
	if err != nil {
		return fmt.Errorf("failed to open database: %w", err)
	}

	DB.SetMaxOpenConns(10)
	DB.SetMaxIdleConns(5)
	DB.SetConnMaxLifetime(time.Hour)

	if err := DB.Ping(); err != nil {
		return fmt.Errorf("failed to ping database: %w", err)
	}

	return nil
}

// InitRedis 初始化Redis连接
func InitRedis() {
	Redis = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", RedisHost, RedisPort),
		Password: RedisPassword,
		DB:       0,
	})
}

// Close 关闭所有连接
func Close() {
	if DB != nil {
		DB.Close()
	}
	if Redis != nil {
		Redis.Close()
	}
}


